Home:ALL Converter>Javascript - await fetch response

Javascript - await fetch response

Ask Time:2020-02-24T01:03:14         Author:stackato

Json Formatter

I have a React-Native app and when the component mounts, I want to fetch data by calling a method in our services class, wait for that data to be returned, then set that data in setState({}). But setState({}) is called before the data is returned.

//Component class

componentDidMount(){
   this.getData();
}

async getData() {
    const data = await MyService.getData();
    this.setState({
        blah:data //undefined
    });
}

//Services Class

let MyService = {
    getData:function(){
        axios.get(url)

    .then(response => response.data)
    .then((data) => {
            //do stuff
          return data;//need to set this to state back in component class
     })
     .catch(error => {
            console.log(error);
     });   
      }
}

module.exports = MyService;

Author:stackato,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/60364658/javascript-await-fetch-response
yy